<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/5/16
 * Time: 01:47
 */

namespace Home\Controller;


use Common\Library\BusinessException;
use Common\Library\CacheRedis;
use Common\Library\Constant;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\SendSMS;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingInfoModel;
use Home\Model\CreditVettingModel;
use Home\Model\FinishModel;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Think\Log;
use Think\Rsa;

class UserCenterController extends Controller {

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    /*********************************************************************
     * 功能描述：我的首页
     * 入参：
     *     "customer_id": "用户ID"
     * 出参：
     *     "code": 0,
     *     "msg": "success",
     *     "data": {
     *     "need_repay_amount": "本月应还总金额,单位分",
     *     "change2instalment_amount": "本月应还的所有可以转为分期还款的总和，单位分";
     *     "bank_card_list": [
     *         {"card_user_name":"持卡人姓名","card_num": "银行卡号", "reserved_mobile": "预留手机号"},
     *         {"card_user_name":"持卡人姓名","card_num": "银行卡号", "reserved_mobile": "预留手机号"}
     *       ]
     *     }
     *********************************************************************/
    public function mine() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $res = D('Customer')->has($customerId);
            if(!$res){
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }
            $repayAmount = 0; //本月应还总金额=消费账单+提现账单
            $consume_bill = 0;//本月应还消费账单
            $withdrawals_bill = 0;//本月应还提现账单
            //$nextMonth2instalment = 0;
            $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
            $ConsumeHistory = M('consume_history')->order('add_time desc')->where(['customer_id' => $customerId])->find();
            
            if($ConsumeHistory['renew_id'] > 0 ){
              $a = $ConsumeHistory['renew_id'];
              $last_day = date('Y-m-d', strtotime("$BeginDate +2 month -1 day"));
            }else {   
                $last_day = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
        }
            
            //1.获取全部的未还款记录-----消费账单
            /**********************************重组消费金额*******h.consume_amount,************************************/
            $sql = 'SELECT h.id,h.consume_amount,h.repayment_time, FROM_UNIXTIME(h.repayment_time, "%Y-%m-%d") AS repay_date, h.amount, h.type,DATEDIFF(FROM_UNIXTIME(h.repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date
                    FROM consume_history h
                    LEFT JOIN customer c ON h.customer_id = c.id
                    WHERE h.customer_id = '.$customerId.' AND h.status IN (1,4) 
                    AND h.amount > 0  AND c.type in (1, 3) ORDER BY h.id DESC';
            
//             echo $sql;
//             $sql = 'SELECT h.id,h.repayment_time, FROM_UNIXTIME(h.repayment_time, "%Y-%m-%d") AS repay_date, h.amount, h.type,DATEDIFF(FROM_UNIXTIME(h.repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date
//                     FROM consume_history h
//                     LEFT JOIN customer c ON h.customer_id = c.id
//                     WHERE h.customer_id = '.$customerId.' AND h.status IN (1,4)
//                     AND h.amount > 0 AND h.type IN (1,2) AND c.type in (1, 3) ORDER BY h.id DESC';
            $billList = M()->query($sql);
            
            if(count($billList)){
                foreach ($billList as $v){
                    /************************重组用户应还款金额*********************************/
                    //天数*百分之二*本金+50
                    if($v['fine_date'][0] == '-'){
                        $amount_ol=$v['consume_amount'];
                        $amount_date=intval(substr($v['fine_date'],1));
                        /*************|判断是否逾期|逾期更改认证状态|**************/
                        if ($amount_date > 0){
                            $scredit = D('CustomerAuth')->saveCustomerAuth($customerId);
                             $czhima = D('Customer')->saveCustomerzhima($customerId);
                            Log::borrow_write("******|mine".$customerId."逾期更改认证状态|结果运营商：".$scredit."芝麻分".$czhima."****：");
//                            if (!$scredit||!$czhima){
//                                Log::borrow_write("******|mine".$customerId."逾期更改认证状态|失败结果".$scredit."****：");
//                                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
//                            }
                            $data = [
                                'accreditation'=>1,
                                'accreditation_status'=>1
                            ];
                            M('Customer')->where(['id'=>$customerId])->setField($data);
                            Log::borrow_write("******|mine".$customerId."逾期更改认证状态|app重推资料".$scredit."****：");
                        }
                        /***************|判断是否逾期|逾期更改认证状态|**************/
                        $amount_fee=Constant::WITHDRAWAL_FINE;
                        $amount_fee_=Constant::OVER_DATE_RATE;
                        //$amount_fee_ = 0;
                        $new_fee=$amount_ol*$amount_date*$amount_fee+$amount_fee_+$amount_ol;
                    }else{
                        $new_fee=$v['consume_amount'];
                    }
                    /*************************重组用户应还款金额*****************************************/
                    if(1 == $v['type'] && ($v['repayment_time'] <= strtotime($last_day))){
                        $consume_bill += $v['amount'];
                       // $nextMonth2instalment = $nextMonth2instalment + $v['amount'];
                        if($v['fine_date'][0] == '-'){//已经逾期
                            if(intval(substr($v['fine_date'], 1))>3){
                                $fine = $v['amount'] * 0.003 * intval(substr($v['fine_date'], 1));
                            }else{
                                $fine = 0;
                            }
                            $consume_bill += $fine;
                        }
                    }else if(2 == $v['type']){//分期还款
                        $sql = 'SELECT amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"),CURDATE()) AS fine_date  FROM consume_installment_history WHERE parent_id = '.$v['id'].'   AND repayment_time <= '.strtotime($last_day).' AND status = 0 ';
                        $install = M()->query($sql);
                        if(count($install)){
                            $fine_all = 0;
                            foreach ($install as $value){
                              $consume_bill +=  $value['amount'];
                              if($value['fine_date'][0] == '-'){
                                  if(intval(substr($value['fine_date'], 1))>3){
                                      $fine_all += $v['amount'] * 0.003 * substr($value['fine_date'], 1);
                                  }
                                }
                            }
                        }
                        $consume_bill += $fine_all;
                    }
                }
            }

            //2获取全部的提现未还款记录----提现账单
            $sql = 'SELECT h.id, h.consume_amount, h.repay_id 
                    FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                    WHERE c.id = '.$customerId." AND h.status = 1
                    AND h.consume_amount > 0 AND h.type = 5 ORDER BY h.id DESC";
            $bill = M()->query($sql);
       if($bill){//存在未还提现账单
            foreach ($bill as $v) {
            $sql = 'SELECT amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"),CURDATE()) AS fine_date 
                       FROM consume_installment_history WHERE parent_id = '.$v['id'].'
                       AND repayment_time <= '.strtotime($last_day).' AND `status` = 0 ';
                $install = M()->query($sql);
                
                if(count($install)){
                    $fine_all = 0;
                  foreach ($install as $value){
                        $withdrawals_bill +=  $value['amount'];
                        if($value['fine_date'][0] == '-'){
                            if(intval(substr($value['fine_date'], 1))>3){
                                $fine_all += $v['consume_amount'] * 0.003 * substr($value['fine_date'], 1);
                            }
                        }
                    }
                }
                $withdrawals_bill += $fine_all;
          }
       }
       
            $bankCardList = D('CustomerBankInfo')->getList($customerId);
            $repayAmount = $repayAmount + intval($consume_bill) + intval($withdrawals_bill);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'need_repay_amount' => $repayAmount,
                //'change2instalment_amount' => $nextMonth2instalment,
                "consume_bill_amount" => intval($consume_bill),
                 "withdrawals_bill_amount" => intval($withdrawals_bill),
                'bank_card_list' => $bankCardList,
                'can_repay_all' => 0,
            ];
            /*************************重组消费金额***********************************/
            if(!isset($new_fee)){
                $new_fee=0;
            }
            $ret['data']['new_fee']=$new_fee;
            //$ret['data']['need_repay_amount']=$new_fee;
            /*************************重组消费金额***********************************/
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 本月账单 （时间没有做过滤，接口有新增字段）bug太多，直接放弃
     */
    /*public function getBillList() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $offset = I('post.offset', 0, 'int');
            $length = I('post.length', 30, 'int');

            D('Customer')->has($customerId);

            // @todo 等数据多的时候直接读分页,而不是将所有数据读出来在分页。
            $consumeList = M('ConsumeHistory')->
                where(['customer_id' => $customerId, 'status'=>['in',"1,4"], 'amount'=>['GT', 0]])
                ->order(['id' => 'desc'])->select();
            $data = [];
            if ($consumeList) {
                $pageConsumeList = array_slice($consumeList, $offset, $length);
                $Merchant = M('Merchant');
                $installmentHistory = D("ConsumeInstallmentHistory");

                foreach ($pageConsumeList as $history) {
                    $merchant_id = $history['merchant_id'];
                    $repay_date = '';
                    //计算当前的还款账单时间
                    $repayTime = $installmentHistory->getRepaymentTime($history);
                    if (empty($history['repayment_time'])) {
                        Log::write('没有还款日期,好奇怪:' . var_export($history, true), Log::ERR);
                    } else {
                        $repay_date = date('Y-m-' . Constant::BILL_LAST_DAY, $repayTime);
                    }

                    if ($history['type'] == Constant::PAY_TYPE_NEXT_MONTH) {
                        $repayAmount = $history['amount'];
                    } else {
                        // 查本月分期该还的金额
                        $repayAmount = $installmentHistory->where(['parent_id'=>$history['id'], 'repayment_time'=>$repayTime])->getField('amount');
                    }
                    $merchantData = $Merchant->where(['id'=>$merchant_id])->find();
                    $data[] = [
                        'consume_id' => $history['id'],
                        'status' => $history['status'],
                        'merchant_name' => $merchantData['name'],
                        'merchant_logo' => C("API_SERVER_HOST").$merchantData['logo'],
                        'repay_type' => $history['type'],
                        'total_amount' => $history['consume_amount'] ? : $history['amount'],
                        'repay_amount' => $repayAmount,
                        'repay_date' => $repay_date,
                        'discount_first_order' => $history['discount_first_order'],
                        'discount_full_reduce' => $history['discount_full_reduce'],
                        'consume_date' => $history['add_time'] ? date('Y-m-d', $history['add_time']) : '',
                    ];
                }
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['total'] = sizeof($consumeList);
            $ret['data'] = $data;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }*/

    public function getBillList() {
        try {
            //0.参数检查
            $customerId = I('post.customer_id', 0, 'int');
            $offset = I('post.offset', 0, 'int');
            $length = I('post.length', 30, 'int');
            Log::write("test:".json_encode(I('post.')), Log::DEBUG);
            if(!$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //获取总的待还款条数
            $count = D('ConsumeHistory')->getConsumeCountWaitRepay($customerId);

            //获取待还款详情信息
            $data = D('ConsumeHistory')->getBillListOnePage($customerId, $offset, $length, $count['next_cnt']);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['offset'] = $offset+$length;
            $ret['length'] = $length;
            $ret['has_next_page'] = ($count['all_cnt']-$ret['offset'])>0 ? 1 : 0;
            $ret['img_url'] = C('ADMIN_SERVER_HOST');
            $ret['data'] = count($data)?$data:[];
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****
     * 获取消费账单（大单） getConsumeBigBillList
     ****/
     public function getConsumeBigBillList(){
             //检查参数
             $customerId = I('post.customer_id', 0, 'int'); //消费者id
             Log::write("test:" . json_encode(I('post.')), Log::DEBUG);
             if (!$customerId) {
                 BusinessException::throwException(Constant::INVALID_PARAMETER);
             }
             //获取消费记录(大单)
             $arr = D('ConsumeHistory')->bigBillCount($customerId);
             $num = $arr[0];
             $consume_ids = $arr[1];
             if($num==1){ //只有一个大单
                 $consume_id = $consume_ids[0]['consume_id'];
                 $ret = D('ConsumeHistory')->getSmallBill($consume_id);
                 $res = Constant::getReturn(Constant::SUCCESS);
                 $res['img_url'] = '';
                 if(date('Y-m-d', $ret['create_time']) < '2016-12-30'){
                     $ret['merchant_logo'] = C('ADMIN_SERVER_HOST').$ret['merchant_logo'];
                 }else{
                     $ret['merchant_logo'] = C('IMAGE_PATH').$ret['merchant_logo'];
                 }
                 $res['type']  = 2;
                 $res['data_small'] = $ret;
             }else{
                 $ret = D('ConsumeHistory')->getBillData($customerId);
                 $res = Constant::getReturn(Constant::SUCCESS);
                 $res['img_url'] = '';
                 foreach($ret as $k=>$v){
                     if(date('Y-m-d', $v['create_time']) < '2016-12-30'){
                         $ret[$k]['merchant_logo'] = C('ADMIN_SERVER_HOST').$v['merchant_logo'];
                     }else{
                         $ret[$k]['merchant_logo'] = C('IMAGE_PATH').$v['merchant_logo'];
                     }
                 }
                 $res['type']  = 1;
                 $res['data_big'] = $ret;
             }
             Response::format($res);
             $this->ajaxReturn($res);
     }
     /********
      * 获取小单接口 getConsumeSmallBillList
      * ****/
      public function getConsumeSmallBillList(){
          $consume_id =I('post.consume_id', 0, 'int');
          $ret = D('ConsumeHistory')->getSmallBill($consume_id);
          $res = Constant::getReturn(Constant::SUCCESS);
          $res['img_url'] = C('ADMIN_SERVER_HOST');
          $res['data'] = $ret;
          Response::format($res);
          $this->ajaxReturn($res);
      }


    /******
     * 测试 付款校验方法 PaymentCheck
     * **/
  /*  public function PaymentCheck(){
      $big_id = I("post.big_id",'0','int');
        $small_id = I('small_id', '', 'string');
      $ret =  D('ConsumeHistory')->PaymentCheck($big_id,$small_id);
        $res = Constant::getReturn(Constant::SUCCESS);
        $res['img_url'] = C('ADMIN_SERVER_HOST');
        $res['data'] = $ret;
        Response::format($res);
        $this->ajaxReturn($res);
    }
*/
    

    /**
     * @todo
     */
    public function repayment() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $amount     = I('post.amount', 0, 'int');
            $consumeId  = I('post.consume_id', 0, 'int');

            D('Customer')->has($customerId);

            if ($consumeId) {
                $consumeHistory = M('ConsumeHistory')->where(['id' => $consumeId])->find();
                if (!$consumeHistory) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }

                if ($amount != $consumeHistory['amount']) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            if (!$amount) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            // @todo 立即还款

            $ret = Constant::getReturn(Constant::ON_MAINTENANCE);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 记算分期信息
     */
    public function calculateInstallment() {
        try {
            $consumeId = I("post.consume_id", 0 , 'intval');
            $customerId = I("post.customer_id", 0, 'intval');
            $consume = D("ConsumeHistory")->where(['id'=>$consumeId, 'customer_id'=>$customerId])->find();
            if (!$consume) {
                BusinessException::throwException(Constant::ERROR_RETURN_DATA);
            }
            $amount = intval($consume['amount']);

            //数据返回
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['consume_amount'] = $amount;
            $repay_time = date('d',$consume['repayment_time']);
            if($repay_time == 31){
                $repay_time = '月底';
            }else{
                $repay_time =  $repay_time.'日';
            }
            //计算分期本金和利息,单位分
            $arr = D('Finish')->getAllInstallmentDetail($amount, $consume['merchant_id'], 1, true);
            foreach ($arr as $k=>$v){
                $arr[$k]['repay_date'] = $repay_time;
            }
            $ret['data'] = $arr;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 确定分期
     * 保存分期
     */
    public function changeToInstallment() {
        try {
            $consume_id = I("post.consume_id", 0 , 'intval');
            $customer_id = I("post.customer_id", 0, 'intval');
            $repay_id = I("post.repay_id", 0, 'intval');
            if (!$customer_id || !$repay_id || !$consume_id) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $consume = D("ConsumeHistory")->where(['id'=>$consume_id, 'customer_id'=>$customer_id])->find();
            if (Constant::PAY_TYPE_NEXT_MONTH != $consume['type'] || !$consume) {
                BusinessException::throwException(Constant::ERROR_RETURN_DATA);
            }
            if($consume['status'] != ConsumeHistoryModel::STATUS_REVIEWED){
                BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
            }
            $amount = intval($consume['amount']);

            //分期数据录入
            $conf = M('SysInstallmentPlan')->where(['id'=>$repay_id, 'publish'=>1, 'target'=>1])->field('repay_times, interest_rate')->find();
            if(!$conf){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            if(!($res = D('Finish')->insConsumeInstallmentDetail($amount, $consume_id, $conf, FinishModel::CURRENT_MONTH_REPAY))){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            //修改次月还款消费记录信息
            $changeConsumeRet = D('ConsumeHistory')->where(['id'=>$consume_id, 'status'=>ConsumeHistoryModel::STATUS_REVIEWED])->
            setField(['status'=>4, 'type'=>Constant::PAY_TYPE_INSTALLMENT, 'repay_id'=>$repay_id]);
            if(!$changeConsumeRet){
                BusinessException::throwException(Constant::FAILED);
            }

            $billModel = D("CustomerBill");
            //次月改分期后，要把原来次月的账单里待还款的金额扣减掉
            if(!($upd = $billModel->updateRepaymentAmount($customer_id, -$amount, date('Y-m', $consume['repayment_time'])))){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            $cur_order = D('ConsumeHistory')->where(['id'=>$consume_id])->find();
            if(!($billId = $billModel->insCustomerBillDetail($cur_order, $conf, FinishModel::CURRENT_MONTH_REPAY))){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            //数据返回
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'amount' => $amount,
                'repay_type' => Constant::PAY_TYPE_INSTALLMENT,
                'repay_date' => Constant::BILL_LAST_DAY,
                'repay_times' => $res['repay_times'],
                'repay_principal' => $res['repay_principal'],
                'repay_interest' => $res['repay_interest'],
                'repay_total' => $res['repay_total'],
            ];

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 上传图片
     * @throws \Think\Exception
     */
    public function uploadImage() {
//Log::upload_write("=======身份证上传=======================");
        try {
            $customerId = I('post.customer_id', 0, 'int');
Log::upload_write("=======客户id".$customerId."传参数据:".json_encode(I('post.'))."|=======================");
            D('Customer')->has($customerId);
            $type = I('post.type', '0', 'string');
            $this->_validateCertType($type);

            // 上传商户合影
            if ($type == Constant::CERT_TYPE_WITH_MERCHANT) {
                $merchantId = I('post.merchant_id', 0, 'int');
                D('Merchant')->has($merchantId);
            }

            //图片上传
            $rootPath = C('UPLOAD_DIR');
            $savePath = '/Customer/';
            $saveName = "{$customerId}_{$type}_";
            $res = D('UploadFile')->uploadImage($rootPath, $savePath, $saveName,1);
            Log::upload_write("=======".$customerId."上传图片结果:".json_encode($res)."上传参数".$rootPath."|".$savePath."|".$saveName."=======================");

            
            if(!$res){
                Log::upload_write("======".$customerId."图片上传失败=======================");

                BusinessException::throwException(Constant::UPLOAD_FAILED);
            }


            $data = [];
            if(is_array($res)){
                foreach ($res as $k=>$v){
                    $data[] = [
                        'customer_id' => $customerId,
                        'file_name' => $res[$k]['savename'],
                        'file_path' => $res[$k]['savepath'],
                        'file_type' => $res[$k]['ext'],
                        'file_size' => $res[$k]['size'],
                        'type' => $type,
                        'status' => Constant::CERT_AUDIT_STATUS_UPLOAD,
                        'add_time' => time(),
                    ];
                }
            }else{
                $data[] = [
                    'customer_id' => $customerId,
                    'file_name' => $res['file']['savename'],
                    'file_path' => $res['file']['savepath'],
                    'file_type' => $res['file']['ext'],
                    'file_size' => $res['file']['size'],
                    'type' => $type,
                    'status' => Constant::CERT_AUDIT_STATUS_UPLOAD,
                    'add_time' => time(),
                ];
            }
            Log::upload_write("=======".$customerId."图片入库数组:".json_encode($data)."=======================");

            if (false === ($ins = M('UploadFile')->addAll($data))) {
                Log::upload_write("======".$customerId."图片入库失败=======================");

                BusinessException::throwException(Constant::FAILED);
            }
	   Log::upload_write("======".$customerId."图片入库结束=======================");
	
            //记录订单照片关系表
            if($type == Constant::CERT_ORDER_CUSTOMER_GOODS || $type == Constant::CERT_ORDER_CUSTOMER_ADMIN ||
                $type == Constant::CERT_ORDER_SEND_GOODS1 || $type == Constant::CERT_ORDER_SEND_GOODS2 ||
                $type == Constant::CERT_ORDER_SEND_GOODS3 || $type == Constant::CERT_ORDER_SEND_GOODS4 ||
                $type == Constant::CERT_ORDER_SEND_GOODS5 || $type == Constant::CERT_TYPE_PROTOCOL){
                $consume_id = I('post.consume_id', 0, 'int');
                if(!$consume_id){
		 Log::upload_write("======".$customerId."|".$consume_id."|消费id不存在=======================");

                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                $upload_data = [
                    'consume_id' => $consume_id,
                    'upload_id'  => $ins,
                    'add_time'   => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time())
                ];

                $insert = M('UploadConsumeRes')->add($upload_data);
                
                if (false === ($insert = M('UploadConsumeRes')->add($upload_data))) {
		  Log::upload_write("======".$customerId."|".json_encode($upload_data)."|添加失败了=======================");
                    BusinessException::throwException(Constant::FAILED);
                }
		 Log::upload_write("======".$customerId."|".json_encode($upload_data)."|添加成功了=======================");

            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
	    Log::upload_write("图片入库失败 : "."code = ".$e->getCode()."; msg = ".$e->getMessage());
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
	 Log::upload_write("======".$customerId."的返回结果:".json_encode($ret)."=======================");

        $this->ajaxReturn($ret);
    }

    private function _validateCertType($type) {
        $validCertType = [
            Constant::CERT_TYPE_WITH_MERCHANT => '',
            Constant::CERT_TYPE_WORKER => '',
            Constant::CERT_TYPE_CREDIT_CARD => '',
            Constant::CERT_TYPE_RESIDENCE_BOOKLET => '',
            Constant::CERT_TYPE_MARRIAGE => '',
            Constant::CERT_TYPE_HOUSE => '',
            Constant::CERT_TYPE_DRIVER => '',
            Constant:: CERT_TYPE_IDCRAD_FACE => '',
            Constant:: CERT_TYPE_IDCRAD_LATER => '',
            Constant:: CERT_TYPE_IDCRADS => '',
            Constant::CERT_TYPE_PROTOCOL => '',
            Constant::CERT_ORDER_CUSTOMER_ADMIN => '',
            Constant::CERT_ORDER_CUSTOMER_GOODS => '',
            Constant::CERT_ORDER_SEND_GOODS1 => '',
            Constant::CERT_ORDER_SEND_GOODS2 => '',
            Constant::CERT_ORDER_SEND_GOODS3 => '',
            Constant::CERT_ORDER_SEND_GOODS4 => '',
            Constant::CERT_ORDER_SEND_GOODS5 => '',
        ];

        if (!isset($validCertType[$type])) {
            BusinessException::throwException(Constant::INVALID_CERT_TYPE);
        }
    }

    /**
     * 获取银行卡列表
     */
    public function getBankList() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = D('CustomerBankInfo')->getList($customerId);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }


   /**
     * 获取可绑定的银行卡列表
     */
    public function getAllBankList() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);
            $bank_arr =array(
                'CCB'=>'建设银行',
                'ABC'=>'农业银行',
                'BOC'=>'中国银行',
                'ICBC'=>'工商银行',
                 'CMB'=>'招商银行',
                'CMBC'=>'民生银行',
                'CEB'=>'光大银行',
                'CIB'=>'兴业银行',
                'PSBC'=>'邮政储蓄',
                'GDB'=>'广发银行',
                'SPAB'=>'平安银行',
                'COMM'=>'交通银行',
                'CITIC'=>'中信银行',
                'SPDB'=>'浦发银行',
                'BOSC'=>'上海银行',
                'Huaxia Bank'=>'华夏银行',
                /**/
            );
            foreach($bank_arr as $k=>$v) {
                $result[] = array('bank_id'=>$k,'bank_name'=>$v);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $result;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * @throws
     * @throws \Think\Exception
     * @throws int
     * @throws string
     */
    public function bindBankCard() {
        try {

            $customer_id    = I('post.customer_id', 0, 'int');

            $cardUserName   = I('post.card_user_name', '', 'string');
            $cardNum        = I('post.card_num', 0, 'string');
            $reservedMobile = I('post.reserved_mobile', 0, 'mobile');
            $verifyCode     = I('post.verify_code', 0, 'int');

            if (!$cardUserName || !$cardNum || !$reservedMobile || !$verifyCode) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $sentVerifyCode = SendSMS::getVerifyCode($reservedMobile, $_type=Constant::VERIFY_CODE_TYPE_BIND);
            if (!$sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }

            if (!$verifyCode || $verifyCode !== $sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            D('Customer')->has($customer_id);

            $map = [
                'customer_id' => $customer_id,
                'card_num' => $cardNum,
            ];

            $CustomerBankInfo = M('CustomerBankInfo');
            if ($CustomerBankInfo->Where($map)->find()) {
                BusinessException::throwException(Constant::BAND_CARD_EXIST);
            }

            $data = [
                'card_user_name' => $cardUserName,
                'reserved_mobile' => $reservedMobile,
                'add_time' => time(),
            ] + $map;

            if (false === ($insertId = $CustomerBankInfo->add($data))) {
                BusinessException::throwException(Constant::BAND_CARD_ADD_FAILED);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $CustomerBankInfo->where(['id' => $insertId])->find();
            SendSMS::rmVerifyCode($reservedMobile, Constant::VERIFY_CODE_TYPE_BIND);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getCertUploadStatus() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $certList = D('UploadFile')->getCustomerCertList($customerId);
            $data = [];
            if ($certList) {
                foreach ($certList as $cert) {
                    $data[] = [
                        'id' => $cert['id'],
                        'type' => $cert['type'],
                        'photo_url' => $this->_getCertImageUrl($cert),
                        'status' => $cert['status'],
                    ];
                }
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $data;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    private function _getCertImageUrl($cert) {
        return C('API_SERVER_HOST') . '/' . C('UPLOAD_DIR') . $cert['file_path'] . $cert['file_name'];
    }

    //下载渠道记录来源
    public function qudaoChannel(){
       //print_r($_POST);exit;
        if(I('post.qudao')) {
            $channel_id = I('post.channel_id', '', 'string');
            $deviceId = I('post.device_id', 'unknown', 'string');
            $data['device_id'] = $deviceId;
            $data['channel_id'] = $channel_id;
            $cid =  M('channel')->add($data);
            if ($cid >0) {
               die('1');
            }
        }
    }

    /*云峰|短信回掉*/
    public  function  yunfeng_notify(){
        $xml=file_get_contents("php://input");
        Log::sms_write("【******************云峰短信回掉|接口返回数据：".$xml."**********】");
        //转换成array
        $array_data = json_decode(json_encode(simplexml_load_string($xml)), true);
        Log::sms_write("【******************云峰短信回掉|接口返回数据|转成数组|json：".json_encode(simplexml_load_string($xml))."**********】");
        Log::sms_write("【******************云峰短信回掉|head：".json_encode($array_data['head'])."**********】");
        Log::sms_write("【******************云峰短信回掉|head：".json_encode($array_data['body'])."**********】");
        return $array_data;
    }

    /*云峰|短信回掉*/
    /************************
     * @融360|注册
     * @author
     *
     **********************/
    public  function  rong_rsa(){
        $data=[];
        //$data['sign']='';
        $data['name']='test';
        $data['phone']='123';
        $arr=[];
        $arr['k1']='1';
        $arr['k2']='2';
        $data['data']=json_encode($arr);
        //$data['data']['key2']='123';
        $data_=rong_sign($data);
        var_dump($data_);
        $rsa= new Rsa();
        echo "公钥：\n", $rsa->publicKey, "\n";
        echo "私钥：\n", $rsa->privateKey, "\n";

        // 使用公钥加密
        $str = $rsa->publicEncrypt('hello', $rsa->publicKey);
        // 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
        $str = base64_encode($str);
        echo "公钥加密（base64处理过）：\n", $str, "\n";
        $str = base64_decode($str);
        $pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
        echo "公钥解密：\n", $pubstr, "\n";
        $privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
        echo "私钥解密：\n", $privstr, "\n";

        // 使用私钥加密
        $str = $rsa->privateEncrypt('world', $rsa->privateKey);
        // 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
        $str = base64_encode($str);
        echo "私钥加密（base64处理过）：\n", $str, "\n";
        $str = base64_decode($str);
        $pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
        echo "公钥解密：\n", $pubstr, "\n";
        $privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
        echo "私钥解密：\n", $privstr, "\n";
    }
    /**********/
    /**
     * 注册
     */
    public function signUp()
    {
        try {
            /* 旧版注册方式，暂时废弃
             $deviceId = I('post.device_id', '');
            if (!$deviceId) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $customer = D('Customer')->has(['device_id' => $deviceId], $_throwException = false);
            if (!$customer) {
                $data = [
                    'device_id' => $deviceId,
                    'add_time' => time(),
                    'status' => Constant::CUSTOMER_NOUSE
                ];
                $customerId = M('Customer')->add($data);
                if (!$customerId) {
                    BusinessException::throwException(Constant::FAILED);
                }

                $customer = D('Customer')->has($customerId);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $customer;*/

            $deviceId = I('post.device_id', 'unknown', 'string');
            $mobile = I('post.mobile', '', 'string');
            Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile);
            $verifyCode = I('post.verify_code', 0, 'int');
            $password = I('post.password', '', 'string');
            $channel_id = I('post.channel_id', '', 'string');
            $app_name = I('post.application_name', '', 'string');
            $source = I('post.device_type', '', 'string');

            if (!$password || !$deviceId || !$mobile || !$verifyCode) {
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."参数不正确");
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //校验手机号格式及是否已经注册过
            if(!is_mobile($mobile)){
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."手机号无效");

                BusinessException::throwException(Constant::INVALID_MOBILE);
            }
            if(D('Customer')->chkCustomerByMobile($mobile)){
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."手机号已存在");

                BusinessException::throwException(Constant::CUSTOMER_MOBILE_EXIST);
            }

            //验证码正确性校验
            $sentVerifyCode = SendSMS::getVerifyCode($mobile, Constant::VERIFY_CODE_TYPE_SIGNUP);
            Log::sms_write("============================ ***验证码有效性校验***==================================================");
            Log::sms_write('============================ ***验证码有效性校验|用户输入的$verifyCode:'.$verifyCode.'***==================================================');
            Log::sms_write('============================ ***验证码有效性校验|服务端发送的$sentVerifyCode:'.$sentVerifyCode.'***==================================================');

            if (!$sentVerifyCode) {
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."验证码已过期");

                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }

            if ($verifyCode !== $sentVerifyCode) {
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."验证码不匹配");

                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }


            //录入用户基本信息
            $Customer = M('Customer');
            $data = [
                'mobile'    => $mobile,
                'password'  => get_enc_password($password),
                'device_id' => $deviceId,
                'add_time'  => time(),
                'user_resource' => 0
            ];

            $id = $Customer->add($data);

            if (false === ($id)) {
                Log::sms_write("============================ ***验证码有效性校验,手机号：***".$mobile."注册失败");

                BusinessException::throwException(Constant::CUSTOMER_ADD_FAILED);
            }

            //记录统计数据
            Log::write($channel_id, Log::DEBUG);
            if($channel_id){
//              $clinetidList = C("CLINET_ID_LIST");//渠道号
//              $clinetidStr = $clinetidList[$channel_id];//解密之后的渠道号

                $clinetidStr = $channel_id; //渠道统计id;

                //下载激活记录表入库
//                 $info = D('Customer')->addClientUuid($id.'#'.$mobile, $clinetidStr);
                $info = D('Customer')->addClientUuid($id.'#'.$mobile, $clinetidStr,$id,$mobile);
                $date = date("Y-m-d H:i:s",time());
                $datas = [
                    'customer_id'=>$id,
                    'device_type'=>$source,
                    'application_name'=>$app_name,
                    'channel_id'=>$channel_id,
                    'add_time'=>$date,
                ];
                if (empty($source) && $source !== '0') {
                    Log::write("CustomerCome|source". $source);
                    $datas = [
                        'customer_id'=>$id,
                        'application_name'=>'找钱花',
                        'channel_id'=>$channel_id,
                        'add_time'=>$date,
                    ];
                }
                $customerComeAddRes = M('CustomerCome')->add($datas);
                Log::write("CustomerCome|source". $source . "|datas|". json_encode($datas) ."CustomerCome表入库结果|" . $customerComeAddRes . "|1入库成功0未修改_失败");
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data']['customer_id'] = $id;

        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*******************************************************************************************
     * 功能描述：退出登陆
     * 创建日期：2016-08-03
     * 入参：
     *     "customer_id": "用户ID"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *******************************************************************************************/
    public function Logout()
    {
        try {
            //0.获取上行参数
            $customerId = I('post.customer_id', 0, 'int');  //用户ID
            if(!$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);

        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /***********************************************************************
     * 功能描述：用户登录
     * 入参：
     *     "device_id":"设备ID(必填字段)",
     *     "mobile":"用户手机号（通过用户名密码方式登录时才需要）",
     *     "password":"密码（通过用户名密码方式登录时才需要）"
     * 出参：
     *     用户个人信息
     * 修改记录：
     *     1.add 用户名/密码登陆方式 at 2016-08-01
     ***********************************************************************/
    public function signIn()
    {
        try {
            $mobile = I('mobile', '', 'string');
            $password = I('password', '', 'string');
            $pushId = I('push_id', '', 'string');
            /*****************************************2017-10-12 14:50:52****************************************************/
            $deviceId = I('post.device_id', 'unknown', 'string');
            /*****************************************2017-10-12 14:50:52****************************************************/

            //参数校验
            if (!$mobile && !$password) {
                Log::borrow_write("INVALID_PARAMETER".json_encode(I('post.')));
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if (!$mobile) {
                Log::borrow_write("获取手机号失败".$mobile."时间为".date("Y-m-d H:i:s").json_encode(I('post.')));
                BusinessException::throwException("您的登录信息已失效，请在设置中退出账号，重新登录！");
            }else{
                Log::borrow_write("获取手机号正常".$mobile."时间为".date("Y-m-d H:i:s").json_encode(I('post.')));
            }
            //校验手机号格式及是否已经注册过
            if(!is_mobile($mobile)){
                Log::borrow_write("账户异常手机号".$mobile."时间为".date("Y-m-d H:i:s"));
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }
            if(!($customer = D('Customer')->chkCustomerByMobile($mobile))){
                Log::borrow_write("CUSTOMER_NOT_FOUND".date("Y-m-d H:i:s").json_encode(I('post.')));
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }
            if($customer['count'] > 1){
                Log::borrow_write("MOBILE_ON_MORE_ACCOUNT".date("Y-m-d H:i:s").json_encode(I('post.')));
                BusinessException::throwException(Constant::MOBILE_ON_MORE_ACCOUNT);
            }
            //保存用户的push_id
            if($pushId){
                $set = M('Customer')->where(['id'=>$customer['id']])->setField(['push_id'=>$pushId]);
                Log::write("用户当前信息：".json_encode($customer), "INFO");
            }
            /*****************************************2017-10-12 14:50:52****************************************************/
            //保存用户的device_id
            if($deviceId){
                $setfieldres = M('Customer')->where(['id'=>$customer['id']])->setField(['device_id'=>$deviceId]);
                Log::write("接收到的用户当前device_id：". $deviceId . "customer表入库结果|" . $setfieldres . "|1入库成功0未修改_失败");
            }
            /*****************************************2017-10-12 14:50:52****************************************************/
            /***************************************cpg2017-10-12 17:14:45****************************************************/
            $cpg = $customer['id'];
            $cpgCustomerInfo = M('Customer')->field('id')->where("id = '$cpg' and add_time > 1507721400 and add_time < 1507788000")->find();
            Log::write("接收到的用户当前device_id：". $deviceId . "customer表入库结果|" . $setfieldres . "|1入库成功0未修改_失败");
            $need_catch_call = 0;
            if ( !empty($cpgCustomerInfo['id']) ) {
                //当查到是那个时候注册的用户那么继续
                $cpgInfo = M('ConsumeHistory')->field('customer_id')->where("customer_id = '$cpg' and type = 4 and status in (5,6) and add_time > 1507721400 and add_time < 1507788000")->find();//查看是否是2017-10-11 19:30:00 - 2017-10-12 14:00:00的用户

                if ( !empty($cpgInfo['customer_id']) ) {
                    //当查到并且还有申请记录，那么继续查是否有入库customer_contact表数据
                    $cpgResult = M('CustomerContact')->where("customer_id = '$cpg' ")->order("add_time desc")->find();

                    if ( empty($cpgResult) ) {
                        //当查出来确实没有那么需要抓通讯录和通话记录
                        $need_catch_call = 1;
                        Log::borrow_write("******|signIn|重推".$customer['id']."****：");
                    } else {
                        $need_catch_call = 0;
                    }
                }
            }
            /***************************************cpg2017-10-12 17:14:45****************************************************/

            //密码正确性校验
            if (password_unmatched($password, $customer['password'])) {
                BusinessException::throwException(Constant::PASSWORD_NOT_MATCH);
            }

            //获取用户认证信息
            $customer = D('CustomerAuth')->getCustomerAuthInfo($customer);
            Log::write("用户认证信息：".json_encode($customer), "INFO");

            //获取用户当前最新状态
            $res = D('ConsumeHistory')->getConsumeListByCustomerId($customer['id'], 0, 1);
            $data = D('ConsumeHistory')->getCurOrderStatus($res[0], 'login');

            $cash_res = D('ConsumeHistory')->getWithdrawalListByCustomerId($customer['id'], 0, 1, NULL);

            if(!$cash_res){
                $cash_data['need_pop'] = 0;
                $black = M('BlackList')->where(['id_num'=>$customer['id_num']])->find();
                if($black){
                    $record = M('CustomerPopupLog')->where(['customer_id'=>$customer['id'], 'type'=>1])->find();
                    $cash_data['already_nums'] = isset($record['already_nums']) ? $record['already_nums'] : 0;
                    $cash_data['hope_nums'] = Constant::POPUP_TIMES_DEFLAUT;
                    $cash_data['status'] = ConsumeHistoryModel::STATUS_TONDDUN_FAILED;
                    $cash_data['reason'] = Constant::TIPS_ORDER_FAILED;
                }else{
                    //$cash_data['status'] = ConsumeHistoryModel::STATUS_CASH_REVIEWED;
                    $cash_data['status'] = $cash_res[0]['status'];
                }
            }else{
                $cash_res[0]['customer_id'] = $customer['id'];
                $cash_data = D('ConsumeHistory')->getCurOrderStatus($cash_res[0], 'login');
                if($cash_data['status'] == ConsumeHistoryModel::STATUS_TONDDUN_FAILED || $cash_data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED){
                    $black = M('BlackList')->where(['id_num'=>$customer['id_num']])->find();
                    if($black){
                        $record = M('CustomerPopupLog')->where(['customer_id'=>$customer['id'], 'type'=>1])->find();
                        $cash_data['already_nums'] = isset($record['already_nums']) ? $record['already_nums'] : 0;
                        $cash_data['hope_nums'] = Constant::POPUP_TIMES_DEFLAUT;
                    }else{
                        $cash_data['already_nums'] = 0;
                        $cash_data['hope_nums'] = Constant::POPUP_TIMES_DEFLAUT;
                    }
                }
            }
            Log::write("提现信息：".json_encode($cash_res), "INFO");

            //返回信息
            $ret = Constant::getReturn(Constant::SUCCESS);
            unset($customer['count']);
            $customer['face_pass_score'] = Constant::FACE_PASS_SCORE;
            //后台审核通过后，会增加balance_cash_amount是不对的，这个地方做限制
            if($customer['balance_cash_amount'] > 200000){
                $customer['balance_cash_amount'] = 200000;
            }
            $redis = new Redis();
            $k = "七天产品的用户数量".date("Y-m-d", time());
            $max_num = M('SysInstallmentPlan')->where(['id'=>4])->find();
            $nu = $redis->get($k);
            Log::write("^^^^^^^七天产品^^^^^用户数量".$nu);
            if ($nu > $max_num['max_num']){
                $ret['data']['max_num'] = 1;//七天产品用户已满
            } else {
                $ret['data']['max_num'] = 0;
            }
            if ($cash_data['overdue'] == 1){
                $scredit = D('CustomerAuth')->saveCustomerAuth($customer['id']);
                $czhima = D('Customer')->saveCustomerzhima($customer['id']);
                Log::borrow_write("******|mine".$customer['id']."逾期更改认证状态|结果运营商：".$scredit."芝麻分".$czhima."****：");
                $datas = [
                    'accreditation'=>1,
                    'accreditation_status'=>1
                ];
                M('Customer')->where(['id'=>$customer['id']])->setField($datas);
                Log::borrow_write("******|mine".$customer['id']."逾期更改认证状态|app重推资料".$scredit."****：");
            }
            /*************************************有过拒绝，再次申请，判断是否超过30天****************************************/
            $customer_id = $customer['id'];
            $ConsumeHistoryRefuseInfo = M('ConsumeHistory')->field('customer_id, type, status, add_time')->where("customer_id = '$customer_id' and type = 4 and status = 6")->order('add_time desc')->find();
            //无拒贷记录 续贷用户
            if (empty($ConsumeHistoryRefuseInfo) ) {//当没有拒贷信息时，调用基础信息是否需要重填方法
                $cash_data = $cash_data;
            } else {
                //有拒贷记录
                $refuseGapTime = time() - $ConsumeHistoryRefuseInfo['add_time'];
                if ($refuseGapTime > 30*86400) {

                    $last_consume = M('ConsumeHistory')->field('customer_id, type, status, add_time')->where("customer_id = '$customer_id' ")->order('add_time desc')->find();
                    //如果大于30天了，而且最新的一条是4-6，那么就status == 3,否则按照最新订单的status
                    if ( $last_consume['type'] == 4 && $last_consume['status'] == 6 ) {
                        $cash_data['status'] = 3;
                    } else {
                        $cash_data['status'] = $last_consume['status'];
                    }

                } else {//拒贷没超过30天的进入拒贷页面
                    $cash_data['status'] = 6;
                }

            }
            $status = $cash_data['status'];
            if ($status == 21 || $status == 23 || $status == 24){
                $cash_data['status'] = 5;
            }
            $adminConfigInfo = D('ConsumeHistory')->getAdminConfigInfo();
            foreach ($adminConfigInfo as $key => $value) {
                $cash_data[$key] = $value;
            }
            /*************************************有过拒绝，再次申请，判断是否超过30天****************************************/
            $ret['data']['customer'] = $customer;
            $ret['data']['credit'] = $data;
            $ret['data']['cash_credit'] = $cash_data;
            $ret['data']['engerce_msg'] = '';/*尊敬的客户您好！根据业务发展需要，我公司将微信公众号名称为“找钱花官网”已更改名称为“火眼时代”，并于2017年9月30日正式启用。业务均不受影响。给您带来的不便请您谅解。国庆节和中秋节到来之际，找钱花全体工作人员祝您假期愉快！北京火眼时代科技有限公司找钱花运营团队2017年9月30日*/
            /*受支付通道升级维护影响，2017年12月5日早上6点前，客户暂无法使用APP进行还款。请您关注找钱花微信公众号：火眼时代（zhaoqianhuavip），获取线下还款方式*/
            $ret['data']['need_catch_call'] = $need_catch_call;
            /*****获取已还款金额*****/
            $map =['customer_id'=>$customer['id'],'type'=>5,'status'=>'1']; 
            $has_repayed=M('ConsumeHistory')->field('id,customer_id,part_pay_amount')->where($map)->order('id  desc')->find();
            $ret['data']['has_repayed'] = $has_repayed['part_pay_amount']?$has_repayed['part_pay_amount']:0;
            Log::borrow_write('--signIn--返回app数据'.json_encode($ret));
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*******************************************************************
     * 功能描述：老用户登陆
     * 创建日期：2016-08-02
     *           如果老用户换手机登陆，则要更新该用户的device_id值
     * 入参：
     *      mobile：手机号
     *      password：登陆密码
     *      deviceId：设备id值
     * 出参：
     *     error ：错误码+错误描述
     *     success：用户的个人信息
     *******************************************************************/
    public function login($mobile, $password, $deviceId)
    {
        //判断用户是否存在
        $customer = M('Customer')->where(['mobile' => $mobile, 'status' => Constant::CUSTOMER_USE])->field('id, device_id, pay_pass')->find();
        if ($customer['device_id']) {
            //用户换手机，更新用户最新的device_id值
            /*if ($deviceId != $customer['device_id']) {
                $res = D('Customer')->updateDeviceId($customer['id'], $deviceId);
            }*/
            //校验手机号密码正确性
            if (password_unmatched($password, $customer['pay_pass'])) {
                BusinessException::throwException(Constant::PASSWORD_NOT_MATCH);
            }
            $ret = M('Customer')->where(['id' => $customer['id']])->find();
        } else {
            $ret = Constant::getReturn(Constant::CUSTOMER_NOT_FOUND);
        }
        return $ret;
    }

    /****** 用户付款记录 ******/
    public function getConsumeList(){
        try{
            $customer_id = I('post.customer_id');
            $offset = I('post.offset', 0, 'int');
            $length = I('post.length', 50, 'int');
            if(!$customer_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //验证用户是否存在
            $res = D('Customer')->has($customer_id);

            //获取总条数及list列表
            $count = D('ConsumeHistory')->getConsumeCountByCustomerId($customer_id);
            $list = D('ConsumeHistory')->getConsumeListByCustomerId($customer_id, $offset, $length, "1,4,3,2,8");

            $ret = Constant::getReturn(Constant::SUCCESS);
            $bank = D('CustomerBankInfo')->getList($customer_id);
            if(!$bank){
                $ret['bind_card'] = 0; //未绑定银行卡
            }else{
                $ret['bind_card'] = 1; //绑定银行卡
                $ret['card_num'] = $bank[0]['card_num'];
                $ret['bank_name'] = $bank[0]['card_user_name'];
            }
            $ret['total'] = $count[0]['cnt'];
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['img_url'] = '';
            foreach ($list as $k=>$v){
                if(date('Y-m-d', $v['create_time']) < '2016-12-30'){
                    $list[$k]['merchant_logo'] = C('ADMIN_SERVER_HOST').$v['merchant_logo'];
                }else{
                    $list[$k]['merchant_logo'] = C('IMAGE_PATH').$v['merchant_logo'];
                }
            }
            $ret['data'] = $list;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 用户提现记录 ******/
    public function getWithdrawalsRecord(){
        try{
            $customer_id = I('post.customer_id');
            $offset = I('post.offset', 0, 'int');
            $length = I('post.length', 50, 'int');
            if(!$customer_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //验证用户是否存在
            $res = D('Customer')->has($customer_id);

            //获取总条数及list列表
            $count = D('ConsumeHistory')->getWithdrawalCountByCustomerId($customer_id);
            $list = D('ConsumeHistory')->getWithdrawalListByCustomerId($customer_id, $offset, $length, '1,3');
            foreach ($list as $key => $val){
                $consume_times = $val['consume_time'];
                $time = date("Y-m-d",strtotime($consume_times));
                $list[$key]['consume_time'] = $time;
                if ($val['status'] == 1){
                    $now = time()-86400;
                    if ($now < $val['repayment_time']){
                        $list[$key]['overdue'] = 0;
                    } else {
                        $list[$key]['overdue'] = 1;
                    }
                }
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['total'] = $count[0]['cnt'];
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['data'] = $list;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getWithdrawalsBill() {
        try {
            //0.参数检查
            $customerId = I('post.customer_id', 0, 'int');
            $offset = I('post.offset', 0, 'int');
            $length = I('post.length', 30, 'int');
            Log::write("test:".json_encode(I('post.')), Log::DEBUG);
            if(!$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);
            $count = D('ConsumeHistory')->getWithdrawalCountByCustomerId($customerId);

            $data = D('ConsumeHistory')->getCashBillListOnePage($customerId, $offset, $length);
            
            $consumestatus = M('consumeHistory')->where(['customer_id'=>$customerId])->field('id,status')->find();
            if($consumestatus['status'] == 3) {
                Log::write("取现账单数据：".count($data), Log::INFO);
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['offset'] = $offset+$length;
                $ret['length'] = $length;
                $ret['has_next_page'] = ($count['cnt']-$ret['offset'])>0 ? 1 : 0;
                $ret['data'] = count($data)?$data:[];


            }else {
                Log::write("取现账单数据：".count($data), Log::INFO);
                //$ret = Constant::getReturn(Constant::SUCCESS);
                $ret['offset'] = $offset+$length;
                $ret['length'] = $length;
                $ret['has_next_page'] = ($count['cnt']-$ret['offset'])>0 ? 1 : 0;
                $ret['data'] = count($data)?$data:[];
            }
            
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Log::write("上一个方法结果".json_encode($ret));
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getWithdrawalsBillInfo() {
        try {
            //0.参数检查
            $customer_id = I('post.customer_id', 0, 'int');
            $consume_id = I('post.consume_id', 0, 'int');
            Log::write("test:".json_encode(I('post.')), Log::DEBUG);
            if(!$customer_id || !$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customer_id);

            $data = D('ConsumeHistory')->getCashBillByBillId($consume_id);
            Log::write("取现账单数据：".count($data), Log::INFO);

            $ret = Constant::getReturn(Constant::SUCCESS);

            $ret['data'] = count($data)?$data:[];
            /*****获取已还款金额*****/
            if($data){
                $map =['customer_id'=>$customer_id,'type'=>5,'status'=>'1'];
                $has_repayed=M('ConsumeHistory')->field('id,customer_id,part_pay_amount')->where($map)->order('id  desc')->find();
                $ret['data']['has_repayed'] = $has_repayed['part_pay_amount']?$has_repayed['part_pay_amount']:0;
                $ret['data']['list'][0]['repay_amount']=$ret['data']['list'][0]['repay_amount']-$ret['data']['has_repayed'];
                //------2017-12-5 19:51:31----//
                $partRepayFind = M("ConsumeHistory")->field("part_pay_amount,part_need_pay_amount")->where(['id'=>$consume_id,'type'=>'5','status'=>'1'])->find();
                if (isset($partRepayFind['part_pay_amount']) && !empty($partRepayFind['part_pay_amount'])) {
                    $shengyu_amount = $this->getShengAmount($consume_id);
                    Log::borrow_write('***已经划扣了部分金额|现主动还款剩余金额*******consume_id：'.$consume_id.'|uns_amount|'. $shengyu_amount .'**************start');
                    $ret['data']['list'][0]['repay_amount']=$shengyu_amount;
                }
                //------2017-12-5 19:51:31----//
                Log::borrow_write('--getWithdrawalsBillInfo--返回app数据'.json_encode($ret));
            }
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Log::write("下一个方法结果".json_encode($ret));
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    ///////////2017年12月5日18:55:43、、、、、、
    /**
     * [getShengAmount 剩余金额计算]
     * @param  [type] $consume_id [description]
     * @return [type]             [description]
     */
    private function  getShengAmount($consume_id){
        $res=D("ConsumeHistory")->field("update_time,part_pay_amount,part_need_pay_amount,consume_amount")->where(['id'=>$consume_id])->find();
        //未还金额=（合同金额-已还金额）*2%*天数+未还金额
        //天数（当前时间-部分还款的时间）
        $res['update_time'] = strtotime(date("Y-m-d 00:00:00",$res['update_time']));
        $overday = (strtotime(date('Y-m-d',time()))-$res['update_time'])/24/60/60;
        if($overday>0){//划扣部分金额逾期的时间
            //本金-已还金额
            $amount=$res['consume_amount']-$res['part_pay_amount'];
            $weihuan=ceil($overday*($amount*Constant::Overdue_Interest_Rate))+Constant::OVER_DATE_RATE+$res['part_need_pay_amount'];
            if(($weihuan+$res['part_pay_amount'])>($res['consume_amount']*2)){
                $shengyu_amount=$res['consume_amount']*2-$res['part_pay_amount'];
            }else{
                $shengyu_amount=$weihuan;
            }
        }else if($overday==0){ //划扣部分金额当天又划扣未还金额，此时只划扣未还金额，不涉及逾期
            $shengyu_amount=$res['part_need_pay_amount']+Constant::OVER_DATE_RATE;
        }else if($res['part_pay_amount']>=$res['consume_amount']){ //已还大于等于合同，直接取剩余金额
            $shengyu_amount=$res['part_need_pay_amount'];
        }
        return  $shengyu_amount;
    }
    ///////////2017年12月5日18:55:43、、、、、、

    public function cashVerifyConfirm()
    {
        try{
            //参数校验
            $customer_id = I('post.customer_id', 0, 'int');
            if(!$customer_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //删除通知缓存
            $res = CacheRedis::getKey($customer_id, Constant::PAY_TYPE_WITHDRAWAL_APPLY);
            if($res){
                CacheRedis::removeKey($customer_id, Constant::PAY_TYPE_WITHDRAWAL_APPLY);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getCustomerWithdStatus(){
        try {
            $customer_id = I('customer_id', '', 'string');
            $customer = D('Customer')->has($customer_id);
            $cash_res = D('ConsumeHistory')->getWithdrawalListByCustomerId($customer_id, 0, 1, NULL, 4);
            if(!$cash_res){
                $cash_data['status'] = ConsumeHistoryModel::STATUS_CASH_REVIEWED;
                $cash_data['need_pop'] = 0;
                $cash_data['consume_id'] = 0;
            }else{
                $cash_res[0]['customer_id'] = $customer_id;
                $cash_data = D('ConsumeHistory')->getCurOrderStatus($cash_res[0], 'login');
                $cash_data['amount'] = $customer['cash_amount'];
            }
            Log::write("提现信息：".json_encode($cash_res), "INFO");

            //返回信息
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $cash_data;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getDemographic()
    {
        $false_data = [
            ['mobile'=>'130****0001', 'money'=>'300000'],
            ['mobile'=>'133****2323', 'money'=>'100000'],
            ['mobile'=>'131****0234', 'money'=>'50000'],
            ['mobile'=>'133****4534', 'money'=>'60000'],
            ['mobile'=>'135****6554', 'money' => '40000'],
            ['mobile'=>'136****2444', 'money' => '50000'],
            ['mobile'=>'137****7909', 'money' => '50000'],
            ['mobile'=>'138****6785', 'money' => '60000'],
            ['mobile'=>'139****3279', 'money' => '60000'],
            ['mobile'=>'150****7098', 'money' => '70000'],
            ['mobile'=>'151****2894', 'money' => '80000'],
            ['mobile'=>'152****7623', 'money' => '90000'],
            ['mobile'=>'153****2665', 'money' => '50000'],
            ['mobile'=>'154****2325', 'money' => '60000'],
            ['mobile'=>'155****6274', 'money' => '70000'],
            ['mobile'=>'156****2323', 'money' => '90000'],
            ['mobile'=>'157****6297', 'money' => '100000'],
            ['mobile'=>'158****2674', 'money' => '110000'],
            ['mobile'=>'159****1789', 'money' => '120000'],
            ['mobile'=>'180****1756', 'money' => '130000'],
            ['mobile'=>'181****1065', 'money' => '140000'],
            ['mobile'=>'182****2785', 'money' => '150000'],
            ['mobile'=>'183****8907', 'money' => '160000'],
            ['mobile'=>'184****0967', 'money' => '170000'],
            ['mobile'=>'185****0925', 'money' => '180000'],
            ['mobile'=>'186****2457', 'money' => '190000'],
            ['mobile'=>'187****6758', 'money' => '200000'],
            ['mobile'=>'188****7853', 'money' => '210000'],
            ['mobile'=>'189****2138', 'money' => '220000'],
            ['mobile'=>'130****1324', 'money' => '230000'],
            ['mobile'=>'131****1287', 'money' => '240000'],
            ['mobile'=>'177****1068', 'money' => '250000'],
            ['mobile'=>'132****7909', 'money' => '260000'],
            ['mobile'=>'133****9908', 'money' => '270000'],
            ['mobile'=>'134****0687', 'money' => '280000'],
            ['mobile'=>'135****8769', 'money' => '290000'],
            ['mobile'=>'136****5736', 'money' => '300000'],
            ['mobile'=>'137****5647', 'money' => '50000'],
            ['mobile'=>'138****9789', 'money' => '60000'],
            ['mobile'=>'139****7546', 'money' => '70000'],
            ['mobile'=>'150****4216', 'money' => '80000'],
            ['mobile'=>'151****6453', 'money' => '90000'],
            ['mobile'=>'151****5649', 'money' => '100000'],
            ['mobile'=>'153****7087', 'money' => '120000'],
            ['mobile'=>'154****7908', 'money' => '120000'],
            ['mobile'=>'155****0798', 'money' => '130000'],
            ['mobile'=>'156****8890', 'money' => '140000'],
            ['mobile'=>'188****0897', 'money' => '150000']
        ];

        $customer = M('Customer')->field("CONCAT(left(mobile, 4),'****',RIGHT(mobile, 4)) AS mobile, cash_amount AS money")->where('cash_amount>0')->order('id desc')->limit(30)->select();
        foreach ($false_data as $v){
            $customer[] = $v;
        }
        $count = M('Customer')->count();
        $key = array_rand($customer, 20);
        $ret = Constant::getReturn(Constant::SUCCESS);
        $ret['apply_count'] = $count*5 + 130863;
        foreach ($key as $v){
            $data[] = $customer[$v];
        }
        $ret['data'] = $data;

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
}
